//
//  HDGDragView.m
//  DGCircleDemo
//
//  Created by HunDegong on 2024/12/6.
//

#import "HDGDragView.h"

@interface HDGDragView ()

@property (nonatomic, weak, readwrite) UIImageView *topImgView;

@property (nonatomic, weak, readwrite) UIImageView *arrowImgView;

@property (nonatomic, weak, readwrite) UILabel *titleLabel;

@end

@implementation HDGDragView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self initialization];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        [self initialization];
    }
    return self;
}

- (void)initialization
{
    UIImageView *topImgView = [[UIImageView alloc] init];
    topImgView.image = [UIImage imageNamed:@"right_point"];
    [self addSubview:topImgView];
    self.topImgView = topImgView;
    
    UIImageView *arrowImgView = [[UIImageView alloc] init];
    arrowImgView.image = [UIImage imageNamed:@"arrow_up"];
    [self addSubview:arrowImgView];
    self.arrowImgView = arrowImgView;
    
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.textColor = [UIColor colorWithWhite:153.0/255.0 alpha:1.0];
    titleLabel.font = [UIFont systemFontOfSize:12];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    [self addSubview:titleLabel];
    self.titleLabel = titleLabel;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    CGFloat width = [HDGDragView widthWidthText:self.titleLabel.text];
    
    CGFloat imgWH = [HDGDragView defaultPointIconWidth];
    CGFloat imgX = (width - imgWH) / 2.0;
    CGFloat imgY = 0;
    
    self.topImgView.frame = CGRectMake(imgX, imgY, imgWH, imgWH);
    
    CGFloat spacing = -10.0;
    CGFloat arrowWH = 8.0;
    CGFloat arrowX = (width - arrowWH) / 2.0;
    CGFloat arrowY = CGRectGetMaxY(self.topImgView.frame) + spacing;
    self.arrowImgView.frame = CGRectMake(arrowX, arrowY, arrowWH, arrowWH);
    
    CGFloat labelH = 16.0;
    self.titleLabel.frame = CGRectMake(0, CGRectGetMaxY(self.arrowImgView.frame), width, labelH);
}

+ (CGFloat)defaultPointIconWidth
{
    return 40.0;
}

+ (CGFloat)fetchHeight
{
    CGFloat imgWH = [self defaultPointIconWidth];
    CGFloat spacing = -10.0;
    CGFloat arrowWH = 8.0;
    CGFloat labelH = 16.0;
    return imgWH + spacing + arrowWH + labelH;
}

+ (CGFloat)widthWidthText:(NSString *)text
{
    CGFloat textWidth = [text boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 12.0) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:12]} context:nil].size.width;
    CGFloat width = textWidth + 8;
    CGFloat defaultWidth = [self defaultPointIconWidth];
    if (width < defaultWidth) width = defaultWidth;
    return width;
}

@end
